from django.shortcuts import render, get_object_or_404
from django.views.generic import DetailView, ListView
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.utils import timezone
from datetime import timedelta
import operator

# Create your views here.

    
def indexView(request, year = timezone.now().year):
    ## raise error when too high/low TODO
    users = User.objects.all()
    statsDict = {}
    for user in users:
        statsDict[user.username] = Helper.formatToRoundHours(GetServedHours.forYear(user, year))
    #statsDict = reversed(sorted(statsDict.items(), key=operator.itemgetter(1)))
    context = {
        "stats": statsDict.items(),
        "year": year,
    }
    return HttpResponse(render(request, "accountstats/index.html", context))

    
def accountView(request, username):
    user = get_object_or_404(User, username=username) # filtert nach nutzer oder wirft 404
    thisYear = timezone.now().year
    context = {
        "user": user,
        "served_in_30_days": Helper.formatToRoundHours(GetServedHours.thirtyDays(user)),
        "served_this_year": Helper.formatToRoundHours(GetServedHours.forYear(user)),
        "this_year": thisYear,
        "served_overall": Helper.formatToRoundHours(GetServedHours.overall(user)),
    }
    #context = {**context, **addContext}
    return HttpResponse(render(request, "accountstats/account.html", context))

class GetServedHours: # Klasse, die mehrere Methoden beherbergt die Wachstunden in einer bestimmten Zeitspanne zurückgibt
    def thirtyDays(user): # für 30 Tage
        endDate = timezone.now().date()
        startDate = endDate - timedelta(days=30)
        days = user.wachtage.filter(dateStarted__range=[startDate, endDate])
        return Helper.getTimeForDays(days)
        
    def forYear(user, year = timezone.now().year): # für dieses Jahr
        days = user.wachtage.filter(dateStarted__year = year)
        return Helper.getTimeForDays(days)
    
    def overall(user): # für alle
        days = user.wachtage.all()
        return Helper.getTimeForDays(days)

class Helper:
    def getTimeForDays(days): # Hilfsmethode die die Tagesstunden zusammenzählt
        timeServed = timedelta()
        for day in days:
            if day.dateStopped: # nur wenn der entsprechende Tag auch beendet wurde (in Praxis sollte das nur der laufende sein)
                dayTimeServed = day.dateStopped - day.dateStarted
                timeServed += dayTimeServed
        return timeServed

    def formatToRoundHours(tdObj): # gets a timedelta object
        tdObj = tdObj.seconds/60/60 # timedelta only has seconds or days attributes
        return round(tdObj)
        
